﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.IO;
using System.Globalization;
using PdfSharp.Charting;
using BLL;
using Model;
using HRP.Utilidades;

namespace HRP.Private.Impressoes
{
    public partial class Adiantamento : System.Web.UI.Page
    {
        private string font = "Verdana";
        private string TituloLabel = "Adiantamento";
        private string NomeFuncLabel = "Nome";
        private string NumeroFuncLabel = "Numero";
        private string NumContribuinteFuncLabel = "NIF";
        private string DepartamentoLabel = "Sector";
        private string CargoLabel = "Categoria";
        private string ValorLabel = "Valor";
        private string ModoPagamentoLabel = "Modo de Pagamento";
        private string DataLabel = "Data";
        private string DescritivoAdiantamento = "Detalhe do Adiantamento";
        private string AssinaturaLabel = "Assinatura";
        private string DeclaracaoLabel = "(Declaro ter recebido desta Empresa o valor do adiantamento presente neste documento)";
        private string NumContribuinteLabel = "Nº Contribuinte: ";
        private string NomeEmpresaLabel = "Entidade: ";

        protected void Page_Load(object sender, EventArgs e)
        {
           // if (adiantamento != null && funcionario != null && Utilidade.ActualEmpresa != null)
                ImprimirComprovativo();
        }

        private void ImprimirComprovativo()
        {
            int idAdiantamento = 0;
            Int32.TryParse(Request.QueryString["id"], out idAdiantamento);
            hrp_empresas empresa = (hrp_empresas)Session["EmpresaActual"];
            int funcionarioId = 0;
            Int32.TryParse(Request.QueryString["funcId"], out funcionarioId);

            if (idAdiantamento == 0 && funcionarioId == 0)
                return;

            var funcionario = Funcionario_BLL.Instance.ObterFuncionarioPorId1(funcionarioId);

            hrp_cargos cargoFunc = Cargo_BLL.Instance.ObterCargo((int)Session["idclient"], empresa.id, (int)funcionario.id_cargo);
            if (cargoFunc == null)
                return;

            string moeda = utilidades.ObterMoedaEmpresa(empresa.id);
            string nomeCargo = cargoFunc.cargo;

           // var empresa = Empresa_BLL.Instance.ObterEmpresa((int)Session["idclient"], (int)Session["idempresa"]);

            var nomeDepartamento = Departamento_BLL.Instance.ObterDepartamento((int)Session["idclient"], 
               empresa.id , 
                (int)cargoFunc.id_departamento );
            var adiantamento = Funcionario_BLL.Instance.ObterAdiantamento(idAdiantamento);

            bool estadoAdiantamento = adiantamento.estado;

            PdfDocument document = new PdfDocument();
            document.Info.Title = "Comprovativo de Adiantamento";
            document.Info.Author = "HRPortal";
            document.Info.Subject = "Adiantamento " + idAdiantamento;
            PdfPage page = document.AddPage();
            page.Width = XUnit.FromMillimeter(297); // A4
            page.Height = XUnit.FromMillimeter(210);
            string dataRecibo = new CultureInfo("pt-PT").DateTimeFormat.GetMonthName(Convert.ToInt32(adiantamento.mes)) + " " + adiantamento.ano;
            GerarComprovativo(ref page, adiantamento.valor.ToString(), adiantamento.user_timestamp.ToString(DefinicoesSite.DataFormato),
                adiantamento.modo_pagamento, funcionario.nome, funcionario.numero_funcionario.ToString(),
            nomeDepartamento.departamento, nomeCargo, funcionario.nif.ToString(), empresa.nif,
            empresa.nome, Server.MapPath(empresa.logo), dataRecibo, moeda, estadoAdiantamento);


            // Send PDF to browser
            MemoryStream stream = new MemoryStream();
            document.Save(stream, false);
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", stream.Length.ToString());
            Response.BinaryWrite(stream.ToArray());
            Response.Flush();
            stream.Close();
            Response.End();
        }

        private void GerarComprovativo(ref PdfPage page, string valorAdiantamento, string dataAdiantamento, string modoPagamentoAdiantamento, string nomeFuncionario,
            string numFuncionario, string depFunc, string cargoFunc, string nifFunc, string nifEmpresa, string nomeEmpresa,
            string logoEmpresaUrl, string mesRecibo, string moeda, bool estadoAdiantamento)
        {
            XGraphics gfx = XGraphics.FromPdfPage(page);
            //Rectangle rectangle = new Rectangle(1,1,840,590);
            XRect rectOriginal = new XRect(10, 15, 400, 560);
            gfx.DrawRectangle(XPens.Black, rectOriginal);
            XRect rectDuplicado = new XRect(430, 15, 400, 560);
            gfx.DrawRectangle(XPens.Black, rectDuplicado);

            /***************ORIGINAL***************************************************/

            //logotipo
            XImage logotipo = XImage.FromFile(logoEmpresaUrl);
            XRect rectLogotipo = new XRect(20, 20, 180, 90);
            gfx.DrawImage(logotipo, rectLogotipo);
            //rect do recibo + data
            int posTitulo = 220;
            string tipoRecibo = "Original";
            int posTipoRecibo = 220;
            int posMesRecibo = 220;
            gfx.DrawString(TituloLabel, new XFont(font, 14, XFontStyle.Bold), XBrushes.Black, posTitulo, 35);
            gfx.DrawString(tipoRecibo, new XFont(font, 10), XBrushes.Black, posTipoRecibo, 48);
            gfx.DrawString(mesRecibo, new XFont(font, 12, XFontStyle.Bold), XBrushes.Black, posMesRecibo, 70);
            //dados Empresa
            gfx.DrawString(NomeEmpresaLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, 220, 90);

            int posNomeEmpresa = 220 + 8 + NomeEmpresaLabel.Length * 4;
            int posNifEmpresa = 220 + 8 + NumContribuinteLabel.Length * 4;
            string primeiroNome = nomeEmpresa;
            string segundoNome = "";
            if (nomeEmpresa.Length > 32)
            {
                string primeiraMetade = nomeEmpresa.Substring(0, 32);
                int ultimoEspaco = primeiraMetade.LastIndexOf(' ');
                primeiroNome = nomeEmpresa.Substring(0, ultimoEspaco);
                segundoNome = nomeEmpresa.Substring(ultimoEspaco + 1, Math.Min(32, nomeEmpresa.Length - ultimoEspaco - 1));
            }
            if (string.IsNullOrEmpty(segundoNome))
            {
                gfx.DrawString(NumContribuinteLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, 220, 100);
                gfx.DrawString(nomeEmpresa, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 90);
                gfx.DrawString(nifEmpresa, new XFont(font, 8), XBrushes.Black, posNifEmpresa, 100);
            }
            else
            {
                gfx.DrawString(NumContribuinteLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, 220, 110);
                gfx.DrawString(primeiroNome, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 90);
                gfx.DrawString(segundoNome, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 100);
                gfx.DrawString(nifEmpresa, new XFont(font, 8), XBrushes.Black, posNifEmpresa, 110);
            }

            //dados funcionario
            XRect rectNomeFunc = new XRect(20, 120, 384, 20);
            XRect rectNumeroFunc = new XRect(20, 140, 114, 20);
            XRect rectNifFunc = new XRect(20, 160, 114, 20);
            XRect rectDepartFunc = new XRect(134, 140, 270, 20);
            XRect rectCargoFunc = new XRect(134, 160, 270, 20);
            gfx.DrawRectangle(XPens.Black, rectNomeFunc);
            gfx.DrawRectangle(XPens.Black, rectNumeroFunc);
            gfx.DrawRectangle(XPens.Black, rectDepartFunc);
            gfx.DrawRectangle(XPens.Black, rectNifFunc);
            gfx.DrawRectangle(XPens.Black, rectCargoFunc);

            XRect rectNomeLabel = new XRect(20, 120, 50, 20);
            XRect rectNumeroLabel = new XRect(20, 140, 50, 20);
            XRect rectNifLabel = new XRect(20, 160, 50, 20);
            XRect rectDepartLabel = new XRect(134, 140, 60, 20);
            XRect rectCargoLabel = new XRect(134, 160, 60, 20);
            gfx.DrawRectangle(XPens.Black, rectNomeLabel);
            gfx.DrawRectangle(XPens.Black, rectNumeroLabel);
            gfx.DrawRectangle(XPens.Black, rectDepartLabel);
            gfx.DrawRectangle(XPens.Black, rectNifLabel);
            gfx.DrawRectangle(XPens.Black, rectCargoLabel);

            gfx.DrawString(NomeFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 22, 135);
            gfx.DrawString(NumeroFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 22, 155);
            gfx.DrawString(NumContribuinteFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 22, 175);
            gfx.DrawString(DepartamentoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 136, 155);
            gfx.DrawString(CargoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 136, 175);
            //insercao dados funcionario
            gfx.DrawString(nomeFuncionario, new XFont(font, 10), XBrushes.Black, 72, 135);
            gfx.DrawString(numFuncionario, new XFont(font, 10), XBrushes.Black, 72, 155);
            gfx.DrawString(nifFunc, new XFont(font, 10), XBrushes.Black, 72, 175);
            gfx.DrawString(depFunc, new XFont(font, 10), XBrushes.Black, 196, 155);
            gfx.DrawString(cargoFunc, new XFont(font, 10), XBrushes.Black, 196, 175);

            gfx.DrawString(DescritivoAdiantamento, new XFont(font, 12, XFontStyle.Bold), XBrushes.Black, 20, 220);
            //cabecalho tabela
            XRect rectValor = new XRect(20, 240, 384, 20);
            XRect rectData = new XRect(20, 260, 384, 20);
            XRect rectModoPag = new XRect(20, 280, 384, 20);
            gfx.DrawRectangle(XPens.Black, rectValor);
            gfx.DrawRectangle(XPens.Black, rectData);
            gfx.DrawRectangle(XPens.Black, rectModoPag);
            gfx.DrawLine(XPens.Black, new XPoint(148, 240), new XPoint(148, 300));
            gfx.DrawString(ValorLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 25, 255);
            gfx.DrawString(DataLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 25, 275);
            gfx.DrawString(ModoPagamentoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 25, 295);

            //LinhasEsq
            string estado = "";
            if (estadoAdiantamento==false)
            {
                estado = "CANCELADO";
            }

            gfx.DrawString(valorAdiantamento + " " + moeda + " " + estado, new XFont(font, 10), XBrushes.Black, 153, 255);
            gfx.DrawString(dataAdiantamento, new XFont(font, 10), XBrushes.Black, 153, 275);
            gfx.DrawString(modoPagamentoAdiantamento, new XFont(font, 10), XBrushes.Black, 153, 295);

            int alturaAssinatura = 480;

            XRect rectAssinData = new XRect(20, alturaAssinatura, 384, 20);
            XRect rectAssin = new XRect(20, alturaAssinatura + 20, 384, 40);
            XRect rectAssinMsg = new XRect(20, alturaAssinatura + 60, 384, 20);
            gfx.DrawRectangle(XPens.Black, rectAssinData);
            gfx.DrawRectangle(XPens.Black, rectAssin);
            gfx.DrawRectangle(XPens.Black, rectAssinMsg);
            gfx.DrawLine(XPens.Black, new XPoint(122, alturaAssinatura), new XPoint(122, alturaAssinatura + 60));
            gfx.DrawString(DataLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 25, alturaAssinatura + 15);
            gfx.DrawString(AssinaturaLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, 25, alturaAssinatura + 42);
            gfx.DrawString(DeclaracaoLabel, new XFont(font, 7, XFontStyle.Bold), XBrushes.Black, 25, alturaAssinatura + 75);



            /***************DUPLICADO***************************************************/
            int posXDuplicadoInicial = 420;
            //logotipo
            rectLogotipo = new XRect(posXDuplicadoInicial + 20, 20, 180, 90);
            gfx.DrawImage(logotipo, rectLogotipo);
            //rect do recibo + data
            posTitulo = posXDuplicadoInicial + 220;
            tipoRecibo = "Duplicado";
            posTipoRecibo = posXDuplicadoInicial + 220;
            posMesRecibo = posXDuplicadoInicial + 220;
            gfx.DrawString(TituloLabel, new XFont(font, 14, XFontStyle.Bold), XBrushes.Black, posTitulo, 35);
            gfx.DrawString(tipoRecibo, new XFont(font, 10), XBrushes.Black, posTipoRecibo, 48);
            gfx.DrawString(mesRecibo, new XFont(font, 12, XFontStyle.Bold), XBrushes.Black, posMesRecibo, 70);
            //dados Empresa
            gfx.DrawString(NomeEmpresaLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 220, 90);

            posNomeEmpresa = posXDuplicadoInicial + 220 + 8 + NomeEmpresaLabel.Length * 4;
            posNifEmpresa = posXDuplicadoInicial + 220 + 8 + NumContribuinteLabel.Length * 4;
            primeiroNome = nomeEmpresa;
            segundoNome = "";
            if (nomeEmpresa.Length > 32)
            {
                string primeiraMetade = nomeEmpresa.Substring(0, 32);
                int ultimoEspaco = primeiraMetade.LastIndexOf(' ');
                primeiroNome = nomeEmpresa.Substring(0, ultimoEspaco);
                segundoNome = nomeEmpresa.Substring(ultimoEspaco + 1, Math.Min(32, nomeEmpresa.Length - ultimoEspaco - 1));
            }
            if (string.IsNullOrEmpty(segundoNome))
            {
                gfx.DrawString(NumContribuinteLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 220, 100);
                gfx.DrawString(nomeEmpresa, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 90);
                gfx.DrawString(nifEmpresa, new XFont(font, 8), XBrushes.Black, posNifEmpresa, 100);
            }
            else
            {
                gfx.DrawString(NumContribuinteLabel, new XFont(font, 8, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 220, 110);
                gfx.DrawString(primeiroNome, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 90);
                gfx.DrawString(segundoNome, new XFont(font, 8), XBrushes.Black, posNomeEmpresa, 100);
                gfx.DrawString(nifEmpresa, new XFont(font, 8), XBrushes.Black, posNifEmpresa, 110);
            }

            //dados funcionario
            rectNomeFunc = new XRect(posXDuplicadoInicial + 20, 120, 384, 20);
            rectNumeroFunc = new XRect(posXDuplicadoInicial + 20, 140, 114, 20);
            rectNifFunc = new XRect(posXDuplicadoInicial + 20, 160, 114, 20);
            rectDepartFunc = new XRect(posXDuplicadoInicial + 134, 140, 270, 20);
            rectCargoFunc = new XRect(posXDuplicadoInicial + 134, 160, 270, 20);
            gfx.DrawRectangle(XPens.Black, rectNomeFunc);
            gfx.DrawRectangle(XPens.Black, rectNumeroFunc);
            gfx.DrawRectangle(XPens.Black, rectDepartFunc);
            gfx.DrawRectangle(XPens.Black, rectNifFunc);
            gfx.DrawRectangle(XPens.Black, rectCargoFunc);

            rectNomeLabel = new XRect(posXDuplicadoInicial + 20, 120, 50, 20);
            rectNumeroLabel = new XRect(posXDuplicadoInicial + 20, 140, 50, 20);
            rectNifLabel = new XRect(posXDuplicadoInicial + 20, 160, 50, 20);
            rectDepartLabel = new XRect(posXDuplicadoInicial + 134, 140, 60, 20);
            rectCargoLabel = new XRect(posXDuplicadoInicial + 134, 160, 60, 20);
            gfx.DrawRectangle(XPens.Black, rectNomeLabel);
            gfx.DrawRectangle(XPens.Black, rectNumeroLabel);
            gfx.DrawRectangle(XPens.Black, rectDepartLabel);
            gfx.DrawRectangle(XPens.Black, rectNifLabel);
            gfx.DrawRectangle(XPens.Black, rectCargoLabel);

            gfx.DrawString(NomeFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 22, 135);
            gfx.DrawString(NumeroFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 22, 155);
            gfx.DrawString(NumContribuinteFuncLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 22, 175);
            gfx.DrawString(DepartamentoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 136, 155);
            gfx.DrawString(CargoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 136, 175);
            //insercao dados funcionario
            gfx.DrawString(nomeFuncionario, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 72, 135);
            gfx.DrawString(numFuncionario, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 72, 155);
            gfx.DrawString(nifFunc, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 72, 175);
            gfx.DrawString(depFunc, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 196, 155);
            gfx.DrawString(cargoFunc, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 196, 175);



            gfx.DrawString(DescritivoAdiantamento, new XFont(font, 12, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 20, 220);
            //cabecalho tabela
            rectValor = new XRect(posXDuplicadoInicial + 20, 240, 384, 20);
            rectData = new XRect(posXDuplicadoInicial + 20, 260, 384, 20);
            rectModoPag = new XRect(posXDuplicadoInicial + 20, 280, 384, 20);
            gfx.DrawRectangle(XPens.Black, rectValor);
            gfx.DrawRectangle(XPens.Black, rectData);
            gfx.DrawRectangle(XPens.Black, rectModoPag);
            gfx.DrawLine(XPens.Black, new XPoint(posXDuplicadoInicial + 148, 240), new XPoint(posXDuplicadoInicial + 148, 300));
            gfx.DrawString(ValorLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, 255);
            gfx.DrawString(DataLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, 275);
            gfx.DrawString(ModoPagamentoLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, 295);

            //LinhasEsq
            gfx.DrawString(valorAdiantamento + " " + moeda + " " + estado, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 153, 255);
            gfx.DrawString(dataAdiantamento, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 153, 275);
            gfx.DrawString(modoPagamentoAdiantamento, new XFont(font, 10), XBrushes.Black, posXDuplicadoInicial + 153, 295);

            rectAssinData = new XRect(posXDuplicadoInicial + 20, alturaAssinatura, 384, 20);
            rectAssin = new XRect(posXDuplicadoInicial + 20, alturaAssinatura + 20, 384, 40);
            rectAssinMsg = new XRect(posXDuplicadoInicial + 20, alturaAssinatura + 60, 384, 20);
            gfx.DrawRectangle(XPens.Black, rectAssinData);
            gfx.DrawRectangle(XPens.Black, rectAssin);
            gfx.DrawRectangle(XPens.Black, rectAssinMsg);
            gfx.DrawLine(XPens.Black, new XPoint(posXDuplicadoInicial + 122, alturaAssinatura), new XPoint(posXDuplicadoInicial + 122, alturaAssinatura + 60));
            gfx.DrawString(DataLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, alturaAssinatura + 15);
            gfx.DrawString(AssinaturaLabel, new XFont(font, 10, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, alturaAssinatura + 42);
            gfx.DrawString(DeclaracaoLabel, new XFont(font, 7, XFontStyle.Bold), XBrushes.Black, posXDuplicadoInicial + 25, alturaAssinatura + 75);

        }

    }
}